package com.example.test.security;

import com.example.test.domain.Role;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 自定义权限投票器
 */
@Component
public class CustomAccessDecisionManager implements AccessDecisionManager {
    /**
     * 裁决，确定认证用户是否有权限访问
     * @param authentication 用户认证
     * @param o 受保护对象(FilterInvocation)
     * @param collection 与正在请求的受保护对象相关联的配置属性（可访问的角色列表）
     */
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        if(collection.isEmpty()) return;
        for (ConfigAttribute configAttribute : collection) {
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                if(configAttribute.getAttribute().equals(authority.getAuthority())) return;
            }
        }
        throw new AccessDeniedException("");
    }

    /**
     * 是否支持对应的配置属性
     */
    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return configAttribute.getClass() == Role.class;
    }

    /**
     * 是否支持对应的受保护对象类型
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
